<template>
  <Header></Header>
  <Drawer></Drawer>
  <el-breadcrumb separator="/" style="font-size: 20px;color: #2AB28B;">
    <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item :to="{ path: '/Home' }">{{ labName }}</el-breadcrumb-item>
    <el-breadcrumb-item :to="{ path: '/ChronicList/'+ groupId }">档案管理</el-breadcrumb-item>
    <el-breadcrumb-item>膳食分析</el-breadcrumb-item>
  </el-breadcrumb>

  <div class = 'pageListBotton'>
    <el-button :icon="Expand" color="#ff5722" style="color: white" round @click="pageList">
      档案列表
    </el-button>

    <span class="onBtnRight"  @click="onHome"><img src="../assets/img/pageList_qiehuan.png" alt=""> 更换群体</span>
  </div>

  <ChronicLeft></ChronicLeft>

  <el-card class="right-box-card">
    <el-scrollbar style="height:100%;width: 100%"> <!-- 滚动条 -->
    <div class="content">
      <div class="g_b">
        <div class="g_b_o">
          <div class="pinggus">
            <div class="pg_hd">
              <div>编号</div>
              <div>能量值（kcal）</div>
              <div>名称</div>
              <div>重量（g）</div>
              <div>份数</div>
            </div>
            <el-row  style="height: 400px;width: 100%;"><!--可显示区域-->
            <div class="pg_hs" v-for="(item,index) in list" :key="index">
              <div>{{item.id}}</div>
              <div>{{item.energy}}</div>
              <div>{{item.food_name}}</div>
              <div>{{item.weight}}</div>
              <div>
                <template v-if="!loadings">
                  <el-input-number
                      v-model="item.num"
                      @change="onChange(index, item.num)"
                      :min="0.1"
                      :step="0.1"
                  ></el-input-number>
                </template>
              </div>
            </div>
            </el-row>
          </div>
        </div>
      </div>
    </div>
    <div class="all">
      <span style="margin-right: 5px;font-size:14px">油能量</span>
      <span style="margin-right: 35px;font-size:14px">{{ OilEnergy }}（kcal）</span>
      总能量：
      <input disabled="disabled" class="num1" type="text" v-model="energy" />
      <span style="font-size: 16px;">（kcal）</span>
      <button @click="btn()" style="border: #f56c6c;background: #f56c6c">查看报告</button>
      <button @click="drawer = true" style="border: #e6a23c;background: #e6a23c">体成分分析</button>
      <button @click="btn_fenxi()" style="border: #67c23a;background: #67c23a">膳食报告</button>
      <button @click="get_new()" style="border: #409eff;background: #409eff">重新获取</button>
    </div>
    </el-scrollbar>

    <div :class="{'tan':tan==true,'la':tan==true,'pi':tan==false}">
      <div class="inner">
        <!-- <div class="tu">
          <img src="@/images/icon-area.svg" alt />
        </div>-->
        <!-- <div class="cg">分析完成</div> -->

        <el-drawer
            v-model="drawer"
            title="请选择要操作的内容"

        >
          <div class="drVal">
            <el-tooltip
                class="box-item"
                effect="dark"
                content="点击此按钮进行体成分分析，如果没有反应请多试几次或者联系管理员哦"
                placement="bottom"
            >
              <el-button type="primary" class="btnClick" @click="appraisal">开始体成分测评</el-button>
            </el-tooltip>

          </div>
          <div class="drVal">
            <el-tooltip
                class="box-item"
                effect="dark"
                content="用户测评完成之后，要点击此处，如点击测评无法显示，请先点击测评完毕"
                placement="bottom"
            >
              <el-button type="info" class="btnClick"  @click="guanbi">测评完毕</el-button>
            </el-tooltip>

          </div>
          <div class="drVal">
            <el-tooltip
                class="box-item"
                effect="dark"
                content="点击此按钮可以直接查看报告，此报告为体成分分析仪分析报告，请先进行体成分分析检测"
                placement="bottom"
            >
              <el-button type="success" class="btnClick" @click="goto">查看体成分报告</el-button>
            </el-tooltip>
          </div>
          <div class="drVal">
            <el-tooltip
                class="box-item"
                effect="dark"
                content="膳食模型放好之后不要移动，确认放好之后点击此按钮，否则不会显示最新膳食哦"
                placement="bottom"
            >
              <el-button type="warning" class="btnClick" @click="btn()" >查看报告</el-button>
            </el-tooltip>
          </div>
        </el-drawer>

      </div>
    </div>
  </el-card>



</template>

<script setup>
import { Edit, CirclePlus, Search, Expand,  } from '@element-plus/icons-vue'
import {defineComponent, onMounted, ref, watch, reactive} from 'vue'
import Header from './common/Header.vue';
import ChronicLeft from './common/ChronicLeft.vue';
import {useRoute, useRouter} from "vue-router"
import http, {baseUrl} from "../utils/http";
import Drawer from './common/Drawer.vue';
import {ElMessage} from "element-plus";
import * as api from "../api/loginHttp";
const route = useRoute()
const router = useRouter()
const labName = ref()

const tan =  ref(true)
const loadings = ref(true)
const list = ref({})
const energy = ref(0)
const OilEnergy = ref(0)
const drawer = ref(false)

const groupId = ref()
const id = ref()
const reportId =ref()
const pageList = async () => {
  await router.push({'path': '/ChronicList/' + groupId.value})
}

const onHome = async () => {
  await router.push({'path': '/Home'})
}

const onChange = async (index, value) => {
  list._rawValue[index].energy = (list._rawValue[index].single.energy * value).toFixed(2)
  list._rawValue[index].weight = (list._rawValue[index].single.weight * value).toFixed(2)
  list._rawValue[index].protein = (list._rawValue[index].single.protein * value).toFixed(2)
  list._rawValue[index].fat = (list._rawValue[index].single.fat * value).toFixed(2)
  list._rawValue[index].carbohydrate = (list._rawValue[index].single.carbohydrate * value).toFixed(2)
  list._rawValue[index].calcium = (list._rawValue[index].single.calcium * value).toFixed(2)
  list._rawValue[index].sodium = (list._rawValue[index].single.sodium * value).toFixed(2)
  list._rawValue[index].magnesium = (list._rawValue[index].single.magnesium * value).toFixed(2)
  list._rawValue[index].iron = (list._rawValue[index].single.iron * value).toFixed(2)
  list._rawValue[index].zinc = (list._rawValue[index].single.zinc * value).toFixed(2)
  list._rawValue[index].selenium = (list._rawValue[index].single.selenium * value).toFixed(2)
  list._rawValue[index].vitamin_a = (list._rawValue[index].single.vitamin_a * value).toFixed(2)
  list._rawValue[index].vitamin_e = (list._rawValue[index].single.vitamin_e * value).toFixed(2)
  list._rawValue[index].vitamin_b1 = (list._rawValue[index].single.vitamin_b1 * value).toFixed(2)
  list._rawValue[index].vitamin_b2 = (list._rawValue[index].single.vitamin_b2 * value).toFixed(2)
  list._rawValue[index].vitamin_c = (list._rawValue[index].single.vitamin_c * value).toFixed(2)

  energy.value = 0
  for (let i = 0; i < list._rawValue.length; i++) {
    energy.value = energy.value + Number(list._rawValue[i].energy);
  }
}

const btn_fenxi = async() => {
  let params = {
    'id': reportId.value,
    'user_id':id.value,
    'diet_energy': energy._value,
    'diet':list._rawValue,
    'memberType':2,
  }

  const data = await api.ChronicDiet(params);
  console.log(data,'222') 
  if(data.data.code == 0) {
    ElMessage.error(data.data.msg)
    return false;
  } else {
    const { href } = await router.resolve({
      path:  "/ChronicDietary/"+groupId.value+"/"+id.value+'/'+reportId.value
    });
    window.open(href, "_blank");
  }

}

const get_new = async() => {
  const res = await api.getFood();
}

const appraisal = async ()  => {
  http.get('api/archives/analysis?id='+ id.value+'&type=analysis').then((res)=>{
    if(res.data.code === 0) {
      ElMessage.error(res.data.msg)
    }
  })
}

const guanbi = async ()  => {
  tan.value = false;
  http.get('api/archives/analysis?id='+ id.value+'&type=cancel').then((res)=>{
    if(res.data.code === 0) {
      ElMessage.error(res.data.msg)
    }
  })
}

const goto = async () => {
  const { href } = await router.resolve({
    path:  "/ChronicAnalysis/"+groupId.value+"/"+id.value+"/"+reportId.value
  });
  window.open(href, "_blank");
}


const btn = async() => {
  // // 只要点击文档，那么就将数据保存起来
  // http.get('api/archives/setReportStatus?reportId='+ reportId.value).then((res)=>{
  //   if(res.data.code === 0) {
  //     ElMessage.error(res.data.msg)
  //     return false
  //   }
  // })
  const { href } = await router.resolve({
    path:  "/Chronic_report/"+groupId.value+"/"+id.value+"/"+reportId.value
  });
  window.open(href, "_blank");

}

const fetchData = async () => {
  if(route.params.groupId) {
    groupId.value = route.params.groupId
    id.value = route.params.id
    reportId.value = route.params.reportId
    if (groupId.value == 3) {
      labName.value = '婴幼儿营养测评'
    } else if (groupId.value == 5) {
      labName.value = '孕产妇营养测评'
    } else if (groupId.value == 6) {
      labName.value = '成年人营养测评'
    } else if (groupId.value == 7) {
      labName.value = '慢性病营养测评'
    } else if (groupId.value == 8) {
      labName.value = '团体营养测评'
    }

    let ws = new WebSocket('ws://'+baseUrl+':1234');
    ws.onopen = function(){
      let uid = window.localStorage.getItem("MemberId");
      ws.send(uid);
    };
    ws.onmessage = function(e){
      loadings.value = true
      energy.value = 0
      let WebList = JSON.parse(e.data)
      for (let i = 0; i < WebList.list.length; i++) {
        WebList.list[i].single = {
          energy: WebList.list[i].energy,
          weight: WebList.list[i].weight,
          protein: WebList.list[i].protein,
          fat: WebList.list[i].fat,
          carbohydrate: WebList.list[i].carbohydrate,
          calcium: WebList.list[i].calcium,
          sodium: WebList.list[i].sodium,
          magnesium: WebList.list[i].magnesium,
          iron: WebList.list[i].iron,
          zinc: WebList.list[i].zinc,
          selenium: WebList.list[i].selenium,
          vitamin_a: WebList.list[i].vitamin_a,
          vitamin_e: WebList.list[i].vitamin_e,
          vitamin_b1: WebList.list[i].vitamin_b1,
          vitamin_b2: WebList.list[i].vitamin_b2,
          vitamin_c: WebList.list[i].vitamin_c,
        }
        energy.value = energy.value + Number(WebList.list[i].energy);
      }

      list.value = WebList.list

      setTimeout(() => {
        loadings.value = false
      },1000);
    };

  } else {
    ElMessage.error('栏目编号不得为空')
    await router.push({'path': '/Home'})
  }

}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
@import '../assets/css/common.css';
.BMIprimary {
  width: 268px;
  height: 70px;
  background: #ff5722;
  opacity: 1;
  border-radius: 8px;
  font-size: 24px;
}
.BMIDefault {
  width: 268px;
  height: 70px;
  background: #fff;
  opacity: 1;
  color: #ff5722;
  border-radius: 8px;
  font-size: 24px;
  border:1px solid #ff5722;
}


::v-deep .el-button:focus, .el-button:hover {
  background: #ff5722;
  color: #fff;
}
::v-deep  .el-progress-bar__inner {
  background: #2AB28B;
}
</style>
<style>
.right-box-card {
  margin-left: 2%;
  margin-top: 1%;
  position: static;
  top: calc(260px);
  width: 60%;
  float: left;

}
.right-box-card .content {
  width: 100%;
  height: 82%;
  padding: 0 100px;
  box-sizing: border-box;
  overflow-y: auto;
}
.right-box-card .content .g_b {
  width: 100%;
  display: flex;
  padding: 0px 32px 16px 32px;
  box-sizing: border-box;
}

.right-box-card .content .g_b .g_b_o {
  flex:2.5;
}
.right-box-card .content .g_b .g_b_o .pinggus{
  width: 100%;
}

.right-box-card  .content .g_b .g_b_o .pinggus .pg_hd{
  width: 100%;
  height: 47px;
  line-height: 47px;
  background: #f5f7fa;
  margin-top: 30px;
  border-bottom: 1px solid #e4e7ed;
  padding-left: 8px;
  box-sizing: border-box;
  display: flex;
  color: #333333;
  font-weight: 500;
  font-family: PingFang SC, PingFang SC-Medium;
  text-align: LEFT;
  font-size: 16px;
}
.right-box-card .content .g_b .g_b_o .pinggus .pg_hd div {
  flex: 1;
  text-align: center;
}

.right-box-card .content .g_b .g_b_o .pinggus .pg_hs {
  width: 100%;
  /* height: 140px; */
  border-bottom: 1px solid #e4e7ed;
  padding-left: 8px;
  box-sizing: border-box;
  display: flex;
  font-size: 14px;
  font-family: PingFang SC, PingFang SC-Medium;
  font-weight: 500;
  /* line-height: 140px; */
}

.right-box-card .content .g_b .g_b_o .pinggus .pg_hs div {
  flex: 1;
  text-align: center;
}
.right-box-card .all {
  line-height: 180px;
  font-size: 20px;
  font-weight: 700;
  color: #3ea4aa;
  padding-left: 100px;
}

.right-box-card .all span{
  margin-right: 5px;
  font-size: 14px;
}

.right-box-card .all .num1{

  width: 62px;
  border: none;
  text-align: center;
  font-size: 20px;
  font-weight: 700;
  color: #3ea4aa;
}
.num {
  width: 62px;
  border: none;
  text-align: center;
  background: #fff;
}

.right-box-card .all button {
  display: inline-block;
  width: 96px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  background: #3ea4aa;
  border-radius: 3px;
  color: #ffffff;
  font-size: 16px;
  float: right;
  margin-right: 40px;
  margin-top: 70px;
  border: none;
}
</style>
